from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.utils import timezone
import hashlib


class UserProfileManager(BaseUserManager):
    use_in_migrations = True

    def create_user(self, id, password=None, **extra_fields):
        if not id:
            raise ValueError('用户唯一id必须提供')
        user = self.model(id=id, **extra_fields)
        if password:
            user.set_password(password)
        else:
            raise ValueError('密码必须提供')
        user.save(using=self._db)
        return user

    def create_superuser(self, id, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_active', True)
        if password is None:
            raise ValueError('超级用户必须提供密码')
        return self.create_user(id=id, password=password, **extra_fields)


class UserProfile(AbstractBaseUser, PermissionsMixin):
    id = models.CharField(max_length=64, primary_key=True, unique=True)
    password = models.CharField(max_length=128)
    data_joined = models.DateTimeField(auto_now_add=True)
    is_superuser = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    objects = UserProfileManager()

    USERNAME_FIELD = 'id'
    REQUIRED_FIELDS = []

    class Meta:
        db_table = 'user_profile'


class UserToken(models.Model):
    user = models.OneToOneField(UserProfile, on_delete=models.CASCADE, primary_key=True, related_name='user_token')
    token = models.CharField(max_length=64, unique=True)
    created_at = models.DateTimeField()

    class Meta:
        db_table = 'user_token'

    @staticmethod
    def generate_token_value(password_hash: str, created_at):
        base = f"{password_hash}{int(created_at.timestamp())}CSI"
        return hashlib.sha256(base.encode('utf-8')).hexdigest()

